<template>
<div id="TxSq" class="page-blank">
  <van-nav-bar :title="(modify ? '修改' : '新增') + '门店'" left-arrow @click-left="goBack()"/>
  <div class="flex-body">    
    <van-cell-group>    
      <van-field v-model="form.shopName" required label="门店名称" placeholder="请输入门店名称"/>
      <van-cell title="商家LOGO">
        <div @click="sele('shopPhotBase')" class="van-uploader">
          <div class="van-uploader__upload">
            <div v-if="form.shopPhotBase" style="width: 100%; height: 100%;" :style="`background: url(${ form.shopPhotBase }) center center / cover no-repeat;`"></div>
            <i v-else class="van-icon van-icon-plus van-uploader__upload-icon"></i>
          </div>
        </div>
      </van-cell>
      <van-cell title="商家图片">
        <div @click="sele('shopPhotUrl')" class="van-uploader">
          <div class="van-uploader__upload">
            <div v-if="form.shopPhotUrl" style="width: 100%; height: 100%;" :style="`background: url(${ form.shopPhotUrl }) center center / cover no-repeat;`"></div>
            <i v-else class="van-icon van-icon-plus van-uploader__upload-icon"></i>
          </div>
        </div>
      </van-cell>
      <van-field readonly clickable label="经纬度" :value="form.longitude ? `${ form.longitude },${ form.latitude }` : ''" required placeholder="请选择经纬度" @click="showAction = true"/>
      <van-field v-model="form.region" required label="所在区域" placeholder="请输入所在区域"/>
      <van-field v-model="form.shopSite" required label="详细地址" placeholder="请输入详细地址"/>
      <van-field readonly clickable label="计费时间/小时" :value="form.chargeTime" required placeholder="请选择计费时间" @click="showPickerClick('chargeTime')"/>
      <van-field v-model.number="form.chargeMoney" required label="计费金额/元" placeholder="请输入计费金额"/>
      <van-field v-model.number="form.freeTime" required label="免费时长/分钟" placeholder="请输入免费时长"/>
      <van-field readonly clickable label="每日最高消费" :value="form.highest" required placeholder="请选择每日最高消费" @click="showPickerClick('highest')"/>
      <van-field v-model="form.shopTele" required label="门店电话" placeholder="请输入门店电话"/>
      <van-field v-model="form.shopHours" required label="营业时间" placeholder="请输入营业时间"/>
      <van-field readonly clickable label="门店类型" required :value="form.shopSortId" placeholder="请选择门店类型" @click="showPickerClick('shopSortId')"/>
      <van-field readonly clickable label="门店管理人" :value="form.userName" required placeholder="选择门店管理人" @click="showUserPicker = true"/>
      <van-field readonly clickable clearable label="渠道商" :value="form.qdsName" placeholder="选择渠道商" @click="showQudaoPicker = true">
        <template #button>
          <van-button v-if="form.qdsName" size="small" type="primary" @click.stop="() => {
            form.qdsName = '';
            form.qdsId = '';
          }">清除</van-button>
        </template>
      </van-field>
      <van-field readonly clickable label="业务员" :value="form.salesmanName" placeholder="选择业务员" @click="showSaleManPicker = true" v-if="roleType < 2"/>
      <van-field readonly clickable label="地图显示" :value="form.ifUsable" required placeholder="请选择状态" @click="showPickerClick('ifUsable')"/>
      <van-field readonly clickable label="门店状态" :value="form.status" required placeholder="请选择状态" @click="showPickerClick('status')"/>
    </van-cell-group>
    <van-button round type="info" size="small" :loading="submitLoading" @click="submit">点击提交</van-button>
  </div>

  <van-popup v-model="showPicker" position="bottom">
    <van-picker show-toolbar :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
  </van-popup>
  <van-popup v-model="showQudaoPicker" position="bottom" :style="{ height: '100%' }">
    <choose-user :roleType="4" :cb="(user) => userChange(user, 'qds')" :close="() => showQudaoPicker = false" :oldValue="form.qdsId"></choose-user>
  </van-popup>
  <van-popup v-model="showUserPicker" position="bottom" :style="{ height: '100%' }">
    <choose-user :roleType="null" :cb="(user) => userChange(user, 'user')" :close="() => showUserPicker = false" :oldValue="form.userId"></choose-user>
  </van-popup>
  <van-popup v-model="showSaleManPicker" position="bottom" :style="{ height: '100%' }">
    <choose-user :roleType="2" :cb="(user) => userChange(user, 'salesman')" :close="() => showSaleManPicker = false" :oldValue="form.salesmanId"></choose-user>
  </van-popup>

  <van-popup v-model="mapPicker" position="bottom" :style="{ height:'100%' }">
    <div class="page-blank" style="height: 100%; position: relative;">
      <van-nav-bar title="选择经纬度" left-arrow @click-left="mapPicker = false"/>
      <div class="flex-body" style="overflow: hidden;">
        <iframe id="mapPage" width="100%" height="100%" frameborder=0
          src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=OKTBZ-K4GKD-6YH46-HXEQ2-YKTAT-JOF7W&referer=速帮闪充">
        </iframe>
      </div>
    </div>
  </van-popup>

  <van-action-sheet v-model="showAction" :actions="mapActions" @select="selectAction" cancel-text="取消" @cancel="showAction = false"/>

</div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';
import axios from '@/utils/request';
import ChooseUser from './ChooseUser.vue';
declare const wx: any;
declare const qq: any;

@Component({ components: { ChooseUser } })
export default class TxSq extends Vue {
  roleType: any = this.$store.state.userInfo.roleType

  modify: any = false

  form: any = {
    salesmanName: '',
    salesmanId: '',
    userName: '',
    userId: '',
    shopName: '',
    shopSite: '',
    highest: '20',
    shopPhotBase: '',
    shopHours: '',
    shopPhotUrl: '',
    region: '',
    chargeUnit: '小时',
    longitude: '',
    latitude: '',
    shopTele: '',
    chargeTime: '1',
    chargeMoney: '',
    freeTime: '',
    qdsId: '',
    qdsName: '',
    ifUsable: '显示',
    status: '启用'
  }
  shopPhotUrlList: any = []
  shopPhotBaseList: any = []
  columns: any = []
  
  showUserPicker: any = false
  showSaleManPicker: any = false
  showQudaoPicker: any = false
  showPicker: any = false
  picker: any = {
    name: '',
    ifUsableColumns: [
      { value: 0, text: '显示' },
      { value: 1, text: '隐藏' }
    ],
    statusColumns: [
      { value: 0, text: '启用' },
      { value: 1, text: '停用' }
    ],
    chargeUnitColumns: [
      { value: 0, text: '小时' },
      { value: 1, text: '分钟' }
    ],
    chargeTimeColumns: [
      { value: 30, text: '0.5' },
      { value: 1, text: '1' },
      { value: 2, text: '2' },
      { value: 3, text: '3' }
    ],
    highestColumns: [
      { value: 20, text: '20' },
      { value: 30, text: '30' },
      { value: 40, text: '40' },
      { value: 50, text: '50' },
      { value: 60, text: '60' },
      { value: 70, text: '70' },
      { value: 80, text: '80' }
    ],
    shopSortIdColumns: []
  }

  geocoder: any = null
  
  modifyRefresh(v: any) {
    this.form = JSON.parse( JSON.stringify( v ) );
    this.form.ifUsable = this.picker.ifUsableColumns.find((v: any) => v.value == this.form.ifUsable).text;
    this.form.status = this.picker.statusColumns.find((v: any) => v.value == this.form.status).text;
    this.form.chargeUnit = this.picker.chargeUnitColumns.find((v: any) => v.value == this.form.chargeUnit).text;
    this.form.chargeTime = this.picker.chargeTimeColumns.find((v: any) => v.value == this.form.chargeTime).text;
    let highest = this.picker.highestColumns.find((v: any) => v.value == this.form.highest)
    this.form.highest = highest ? highest.text : '';
    let shopSortId = this.picker.shopSortIdColumns.find((v: any) => v.value == this.form.shopSortId)
    this.form.shopSortId = shopSortId ? shopSortId.text : '';
    this.$nextTick(() => {
      this.form = JSON.parse(JSON.stringify( this.form ));
    });
    this.modify = true;
  }
  
  showPickerClick(name: any) {
    this.picker.name = name;
    this.columns = this.picker[name + 'Columns'];
    this.showPicker = true;
  }
  onConfirm(value: any) {
    this.form[ this.picker.name ] = value.text;
    this.showPicker = false;
  }

  mapPicker: any = false
  showAction: any = false
  mapActions: any = [
    { name: '自动获取位置' },
    { name: '手动选择位置' }
  ]
  selectAction(obj: any) {
    this.showAction = false;
    if( obj.name == '自动获取位置' ) {
      this.getPosiInfo();
    } else {
      this.mapPicker = true;
    }
  }
  getPosiInfo() {
    let config = this.$store.state.config;
    wx.config({ ...config, debug: false, jsApiList: [ 'scanQRCode', 'chooseImage', 'uploadImage', 'getLocation', 'getLocation', 'openLocation' ] });
    wx.getLocation({
      type: 'wgs84', 
      success: (res: any) => {
        var latitude = res.latitude; 
        var longitude = res.longitude;
        this.geocoder.getAddress(new qq.maps.LatLng(latitude, longitude));
        this.form.longitude = longitude;
        this.form.latitude = latitude;
        wx.openLocation({
          latitude, 
          longitude,
          scale: 23,
          infoUrl: ''
        });
      }
    });
  }
  getLocationName(result: any) {
    let detail = result.detail.addressComponents;
    this.form.shopSite = result.detail.address;
    this.form.region = detail.city + detail.district;
  }

  userChange(v: any, type: any) {
    this.form[type + 'Id'] = v.userId;
    this.form[type + 'Name'] = v.userName;
    this.showUserPicker = false;
    this.showSaleManPicker = false;
    this.showQudaoPicker = false;
  }

  sele( url: string ) {
    if(this.$store.state.wxSwitch != 1) return this.$toast('请在微信公众号内打开进行该操作');
    let config = this.$store.state.config;
    wx.config({ ...config, debug: false, jsApiList: [ 'scanQRCode', 'chooseImage', 'uploadImage', 'getLocation', 'openLocation' ] });
    wx.chooseImage({ count: 1, sizeType: [ 'compressed' ], sourceType: [ 'album', 'camera' ], 
      success: (res: any) => {        
        console.log(res, 'chooseRes');
        wx.uploadImage({ localId: res.localIds[ res.localIds.length - 1 ], isShowProgressTips: 1,
          success: (res: any) => {
            console.log('media_id', res.serverId);
            axios.get('/api/upload/getUploadFile', {
              media_id: res.serverId
            }).then((res: any) => {
              if(url == 'shopPhotBase') this.form.shopPhotBase = res;
              else this.form.shopPhotUrl = res;
            });
          }
        });
      }
    });
  }

  submitLoading: any = false
  
  submit() {
    if( this.submitLoading ) return ;
    if(this.form.shopName == '') return this.$toast('请输入门店名称');
    if(this.form.shopPhotBase == '') return this.$toast('请上传商家LOGO');
    if(this.form.shopPhotUrl == '') return this.$toast('请上传商家图片');
    if(this.form.region == '') return this.$toast('请输入所在区域');
    if(this.form.shopSite == '') return this.$toast('请输入详细地址');
    if(this.form.longitude == '') return this.$toast('请选择经纬度');
    if(this.form.chargeTime == '') return this.$toast('请输入计费时间');
    if(!/^5$|^([0-4])(\.\d{1,2})?$/.test(this.form.chargeTime)) return this.$toast('计费时间0-5小时,允许输入最多两位小数或整数');
    if(this.form.chargeMoney == '') return this.$toast('请输入计费金额');
    if(!/^10$|^([1-9])(\.\d{1,2})?$/.test(this.form.chargeMoney)) return this.$toast('计费金额1-10元,允许输入最多两位小数或整数');
    if(this.form.freeTime == '') return this.$toast('请输入免费时长');
    if(!/^([0-9]|[1-5][0-9]|60)$/.test(this.form.freeTime)) return this.$toast('免费时长0-60分钟,请正确输入');
    if(this.form.highest == '') return this.$toast('请选择每日最高消费');
    if(this.form.shopTele == '') return this.$toast('请输入门店电话');
    if(this.form.shopHours == '') return this.$toast('请输入营业时间');
    if(this.form.userId == '') return this.$toast('请选择门店管理人');
    if(this.form.ifUsable == '') return this.$toast('请选择状态');
    if(this.form.shopSortId == '' || !this.form.shopSortId) return this.$toast('请选择门店类型');
    this.submitLoading = true;
    let obj = JSON.parse(JSON.stringify(this.form));
    if(this.$store.state.userInfo.roleType == 2) obj.salesmanId = this.$store.state.userInfo.userId;
    if(obj.shopSortId) obj.shopSortId = this.picker.shopSortIdColumns.find((v: any) => v.text == obj.shopSortId).value;
    obj.ifUsable = this.picker.ifUsableColumns.find((v: any) => v.text == obj.ifUsable).value;
    obj.status = this.picker.statusColumns.find((v: any) => v.text == obj.status).value;
    obj.chargeUnit = obj.chargeTime == '0.5' ? 1 : 0;
    obj.chargeTime = this.picker.chargeTimeColumns.find((v: any) => v.text == obj.chargeTime).value;
    axios.post('/api/ShopManageController/addShopManage', obj).then((res: any) => {
      this.$toast(`${ this.modify ? '修改' : '新增' }成功！`);
      this.$router.go(-1);
      this.submitLoading = false;
    }).catch((err: any) => {
      this.submitLoading = false;
    });
  }

  goBack() {
    this.$router.go(-1);
  }

  mounted() {
    axios.get('/api/ShopSortController/getShopSortList', { page: 1, size: 1000 }).then((res: any) => {      
      let list = res.list || [];
      this.picker.shopSortIdColumns = list.map((item: any) => { return { value: item.shopSortId, text: item.shopSortName } });
      if(this.$route.query && this.$route.query.type) {
        if(this.$route.params && this.$route.params.userId) this.modifyRefresh( this.$route.params );
        else this.goBack();
      }
    });
    // 业务员自动绑定自身
    if(this.$store.state.userInfo.roleType == 2) {
      this.form.salesmanId = this.$store.state.userInfo.userId;
      this.form.salesmanName = this.$store.state.userInfo.userName;
    }

    this.geocoder = new qq.maps.Geocoder({
      complete: this.getLocationName
    });

    window.addEventListener('message', (event: any) => {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') {
        //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        this.form.longitude = loc.latlng.lng;
        this.form.latitude = loc.latlng.lat;
        this.form.shopSite = loc.poiaddress;
        this.form.region = loc.cityname;
        this.mapPicker = false;
      }
    }, false);
  }
  
};
</script>

<style lang="scss">
#TxSq {
}
</style>

